package io.gitee.zhucan123.core.infrastructure.entity;

import com.niimbot.middlend.core.infrastructure.annotation.Immutable;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * Important:
 * 修改了这个类后，需要使用jpamodelgen重新生成，然后更新同一个包中的 BaseEntity_ 文件
 */

/**
 * @author: zhuCan
 * @date: 2019-07-23 14:57
 * @description: 实体类基类 ,用来抽离重复的字段
 */
@Data
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public class BaseEntity {

  public static final String COL_ID = "id";
  public static final String COL_GMT_CREATE = "gmt_create";
  public static final String COL_GMT_MODIFIED_AT = "gmt_modified";

  /**
   * 主键id
   */
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = COL_ID, nullable = false)
  private Long id;

  /**
   * 创建时间
   */
  @Column(name = COL_GMT_CREATE, nullable = false, updatable = false)
  @CreatedDate
  private LocalDateTime createdAt;

  /**
   * 修改时间
   */
  @Column(name = COL_GMT_MODIFIED_AT, nullable = false)
  @LastModifiedDate
  private LocalDateTime modifiedAt;

  /**
   * 修改时 把要修改的对象的非空 字段 赋值到 通过id查询出的对象
   *
   * @param source
   */
  public void copySkipNullValue(Object source) {
    Field[] sourceFields = source.getClass().getDeclaredFields();

    BeanUtils.copyProperties(source, this, Arrays.stream(sourceFields).filter(x -> x.getAnnotation(Immutable.class) != null && !x.getAnnotation(Immutable.class).immutable())
        .map(Field::getName).toArray(String[]::new));
  }
}
